package deepFirstSearch;

import org.apache.ibatis.jdbc.SQL;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class P1 {
    List<Integer[]> freq = new ArrayList<Integer[]>();
    List<List<Integer>> ans = new ArrayList<List<Integer>>();
    List<Integer> sequence = new ArrayList<Integer>();

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        for (int candidate : candidates) {
            int size = freq.size();
            if (freq.isEmpty() || candidate != freq.get(size - 1)[0]) {
                freq.add(new Integer[]{candidate, 1});
            } else {
                freq.get(size - 1)[1]++;
            }
        }
        dfs(0, target);
        return ans;
    }

    private void dfs(int pos, int rest) {
        if (rest == 0) {
            ans.add(new ArrayList<Integer>(sequence));
            return;
        }
        if (pos == freq.size() || rest < freq.get(pos)[0]) {
            return;
        }
        dfs(pos + 1, rest);
        int most = Math.min(rest / freq.get(pos)[0], freq.get(pos)[1]);
        for (int i = 1; i <= most; i++) {
            sequence.add(freq.get(pos)[0]);
            dfs(pos + 1, rest - i * freq.get(pos)[0]);
        }
        for (int i = 1; i <= most; i++) {
            sequence.remove(sequence.size() - 1);
        }
    }

    @Test
    public void test01() {
//        int[] candidates = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40};
        int[] candidates = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int target = 13;
        List<List<Integer>> res = combinationSum2(candidates, target);
        for (List<Integer> re : res) {
            for (Integer ele : re) {
                System.out.print(ele + ", ");
            }
            System.out.println();
        }
    }
}
